const express = require('express')
const path = require('path')
const formidable = require('formidable')

const router = express.Router()
router.post('/', (req, res, next) => {
    //创建formidable实例
    const form = formidable({
        multiples: true, //是否支持多文件上传
        uploadDir: path.join(__dirname, '../public/upload'), //自定义上传目录
        keepExtensions: true //是否保留文件后缀
    });
    //解析请求
    form.parse(req, (err, fields, files) => {
        if (err) {
            next(err);
            return;
        }
        const host = req.get('host')

        for (const key in files) {
            if (Array.isArray(files[key])) {
                files[key].forEach(file => {
                    file.path = `http://${host}/upload/` + /.*\\public\\upload\\(.*)$/.exec(file.path)[1]
                })
            } else {
                files[key].path = `http://${host}/upload/` + /.*\\public\\upload\\(.*)$/.exec(files[key].path)[1]
            }
        }
        res.json({
            code: 200,
            data: {
                fields,
                files
            }

        });
    });
})
module.exports = router